package com.example.web;

import com.example.business.SignService;
import com.example.business.UserService;
import com.example.data.model.SignRequest;
import com.example.data.model.User;
import com.example.utils.AuthToken;
import com.example.utils.DemoTokenComponent;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by hldev on 16-12-9.
 */
@RestController
@RequestMapping("/demo/user")
@Api(value = "api-user", description = "有关用户表的CRUD")
@CrossOrigin
public class UserController {

    private final UserService userService;
    private final SignService signService;
    private final DemoTokenComponent demoTokenComponent;

    @Autowired
    public UserController(UserService userService, SignService signService, DemoTokenComponent demoTokenComponent) {
        this.userService = userService;
        this.signService = signService;
        this.demoTokenComponent = demoTokenComponent;
    }

    @GetMapping(path = "{id}")
    @ApiOperation(value = "根据id查找用户信息", notes = "根据id查找用户信息")
    public User getOne(@PathVariable("id") Integer id) {
        return userService.findOne(id);
    }

    @GetMapping(path = "list")
    @ApiOperation(value = "查找所有用户信息", notes = "查找所有用户信息")
    public List<User> getAll() {
        return userService.findAll();
    }


    @PutMapping
    @ApiOperation(value = "根据id更新一条用户信息", notes = "根据id更新一条用户信息")
    public User updateUser(@RequestBody User user) {
//        if (result.hasErrors()){
//            throw new ValidateException(result);
//        }

        userService.updateUser(user);
        return user;
    }

    @DeleteMapping(path = "{id}")
    @ApiOperation(value = "根据id删除一条用户信息", notes = "根据id删除一条用户信息")
    public ResponseEntity deleteUser(@PathVariable("id") Integer id) {
        userService.deleteUser(id);
        return new ResponseEntity(HttpStatus.OK);
    }

    /**
     * 注册
     */
    @PostMapping
    @ApiOperation(value = "用户注册", notes = "用户注册")
    public User signup(@RequestBody User user) {
        userService.createUser(user);
        return user;
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "用户登录")
    public ResponseEntity<User> login(@RequestBody SignRequest signRequest, HttpServletResponse response) {
        User user = signService.signin(signRequest);
        if (user != null) {
            AuthToken authToken = AuthToken.create(user.getUserName(), user.getId());
            demoTokenComponent.storeAuthTokenToHttpResponse(response, authToken);
            return new ResponseEntity<User>(user, HttpStatus.OK);
        }

        return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
    }

}
